package com.kedacom.demo.springrabbit.test;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

public class RPCServer {

	private static String RABBITMQ_HOST = "172.16.217.217";
	private static String RPC_QUEUE_NAME = "rmq.spring.test.rpc.queue";

	public static void main(String[] args) throws InterruptedException, IOException, TimeoutException {
		MessageHandler messageHandler = new MessageHandler();

		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost(RABBITMQ_HOST);

		Connection connection = factory.newConnection();
		Channel channel = connection.createChannel();

		channel.queueDeclare(RPC_QUEUE_NAME, true, false, false, null);

		channel.basicQos(1);

		QueueingConsumer consumer = new QueueingConsumer(channel);
		channel.basicConsume(RPC_QUEUE_NAME, false, consumer);

		while (true) {
			QueueingConsumer.Delivery delivery = consumer.nextDelivery();

			BasicProperties props = delivery.getProperties();
			BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId())
					.contentType("application/json").build();

			String message = new String(delivery.getBody());
			String result = messageHandler.handleMessage(message);

			channel.basicPublish("", props.getReplyTo(), replyProps, result.getBytes());
			channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
		}
	}

}
